package com.charonmc.utils;

import com.charonmc.CharonLib;
import com.charonmc.utils.mysql.SqlManager;
import lombok.SneakyThrows;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.HashMap;

public class PrefixUtils {
    public static HashMap<Integer, String> prefixTable = new HashMap<>();
    public static HashMap<Player, Integer> playerPrefix = new HashMap<>();

    public static String getPlayerPrefix(Player player){
        return prefixTable.get(playerPrefix.get(player));
    }

    public static void setPlayerPrefix(Player player, Integer prefix){
        PrefixUtils.playerPrefix.put(player, prefix);
        if (prefix == -1){
            player.sendMessage("§7您的称号已取消。");
        } else {
            player.sendMessage("§7您的称号已切换为" + PrefixUtils.prefixTable.get(prefix));
        }
        BukkitRunnable task = new BukkitRunnable() {
            @SneakyThrows
            @Override
            public void run() {
                SqlManager sqlManager = new SqlManager("charonmc");
                Object id = sqlManager.createQuery()
                        .inTable("players")
                        .selectColumns("player_id")
                        .addCondition("player_name", player.getName())
                        .build()
                        .execute()
                        .first();
                sqlManager.createUpdate()
                        .inTable("player_set")
                        .addColumnNames(new String[]{"prefix"})
                        .addParams(new Object[]{prefix})
                        .addCondition("player_id", id)
                        .build()
                        .execute();
                sqlManager.close();
            }
        };
        task.runTaskAsynchronously(CharonLib.instance);
    }

    public static String getPlayerPrefixTiny(Player player){
        return getSubString(prefixTable.get(playerPrefix.get(player)), "[", "]");
    }

    public static String getSubString(String text, String left, String right) {
        String result = "";
        int zLen;
        if (left == null || left.isEmpty()) {
            zLen = 0;
        } else {
            zLen = text.indexOf(left);
            if (zLen > -1) {
                zLen += left.length();
            } else {
                zLen = 0;
            }
        }
        int yLen = text.indexOf(right, zLen);
        if (yLen < 0 || right.isEmpty()) {
            yLen = text.length();
        }
        result = text.substring(zLen, yLen);
        return result;
    }
}
